package cn.felord.mvc.excel.alibaba;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import org.springframework.web.servlet.view.AbstractView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author dax
 * @since 2020/4/6 22:24
 */
public abstract class AbstractAliExcelView extends AbstractView {

    private ExcelTypeEnum excelTypeEnum;

    public AbstractAliExcelView() {
        this.excelTypeEnum = ExcelTypeEnum.XLS;
        setContentType("application/vnd.ms-excel");
    }

    @Override
    protected boolean generatesDownloadContent() {
        return true;
    }

    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType(getContentType());
        // step 1  生成对象
        ExcelWriterBuilder excelWriterBuilder = createExcelWriterBuilder(response);
        doExcelWriter(model, excelWriterBuilder);

    }




    protected ExcelWriterBuilder createExcelWriterBuilder(HttpServletResponse response) throws IOException {
        return EasyExcel.write(response.getOutputStream())
                .excelType(excelTypeEnum)
                .autoCloseStream(true);
    }

    /**
     * 函数钩子
     * @param model
     * @param excelWriterBuilder
     * @return
     */
    protected abstract void doExcelWriter(Map<String, Object> model, ExcelWriterBuilder excelWriterBuilder);

}
